导航菜单
首页 >  Handling File Uploads With NestJS and MySQL  > Implementing File Uploads in NestJS Fastify: A Step

Implementing File Uploads in NestJS Fastify: A Step

import { BadRequestException, CallHandler, ExecutionContext, NestInterceptor,} from '@nestjs/common';import { FastifyRequest } from 'fastify';import { Observable } from 'rxjs';import { find } from 'lodash';import { MultipartFile } from '@fastify/multipart';

export class FileTransformInterceptor implements NestInterceptor { private async streamToString(multipartFile: MultipartFile): Promise {const stream = multipartFile.file;const chunks = [];return new Promise((resolve, reject) => { stream.on('data', (chunk) => {chunks.push(Buffer.from(chunk)); }); stream.on('error', (err) => {reject(err); }); stream.on('end', () => {return resolve(Buffer.concat(chunks).toString('utf8')); }); stream.on('limit', () => {reject(new BadRequestException('File size limit exceeded')); });}); } private validateAndGetFileType(filename: string, mimetype: string) {const nameSplits = filename.split('.');const extension = nameSplits[nameSplits.length - 1];const supportedTypes = [ { extension: 'json', mimetype: 'application/json' },];const typeCheckResult = find(supportedTypes, { extension }) || find(supportedTypes, { mimetype });if (!typeCheckResult) { throw new BadRequestException('File type not supported');}return typeCheckResult.type; } async intercept(context: ExecutionContext,next: CallHandler, ): Promise {const req = context.switchToHttp().getRequest();if (!req.isMultipart()) { throw new BadRequestException('Request must be multipart');}const multipartFile = await req.file();if (!multipartFile) { throw new BadRequestException('File required');}

this.validateAndGetFileType(multipartFile.filename, multipartFile.mimetype);const fileContents = await this.streamToString(multipartFile);

try { req.body = JSON.parse(fileContents);} catch (err) { throw new BadRequestException('Invalid JSON format');}return next.handle(); }}

相关推荐: